package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"gitee.com/xuender/kits/cmd"
	"gitee.com/xuender/oils/base"
	"gitee.com/xuender/oils/logs"
	"github.com/golang/snappy"
)

func main() {
	var (
		out          string
		decompressor bool
	)

	flag.Usage = usage
	flag.StringVar(&out, "o", "", "output file")
	flag.BoolVar(&decompressor, "d", false, "decompressor")
	flag.Parse()

	defer Panic()

	var inReader io.Reader
	if len(flag.Args()) == 0 {
		inReader = os.Stdin
	} else {
		check(flag.Arg(0))
		file := base.Panic1(filepath.Abs(flag.Arg(0)))
		reader := base.Panic1(os.Open(file))
		inReader = reader

		defer reader.Close()
	}

	logs.Debug("start")

	var outWriter io.Writer
	if out == "" {
		outWriter = os.Stdout
	} else {
		if !decompressor && filepath.Ext(out) == "" {
			out += ".snappy"
		}

		file := base.Panic1(filepath.Abs(out))
		outWriter = base.Panic1(os.Create(file))
	}

	if decompressor {
		reader := snappy.NewReader(inReader)
		base.Panic1(io.Copy(outWriter, reader))

		logs.Info("Extract done.")

		return
	}

	writer := snappy.NewWriter(outWriter)
	defer writer.Close()

	base.Panic1(io.Copy(writer, inReader))
	logs.Info("Snappy done.")
}

func check(path string) {
	logs.Debugw("check", "path", path)

	file := base.Panic1(filepath.Abs(path))
	fileInfo := base.Panic1(os.Stat(file))

	if fileInfo.IsDir() {
		panic(path + "is dir")
	}
}

func usage() {
	fmt.Fprintf(flag.CommandLine.Output(), "kit-snappy [%s]\n\n", cmd.ModVersion)
	fmt.Fprintf(flag.CommandLine.Output(), "A fast compressor/decompressor.\n\n")
	fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(flag.CommandLine.Output(), `
Examples:
	ls -la | kit-snappy > ls.snappy
	kit-snappy -o demo.snappy demo.txt
	kit-snappy -o ls.txt -d ls.snappy
`)
	fmt.Fprintf(flag.CommandLine.Output(), "\nmod: %s\ngit: %s\n", cmd.ModPath, cmd.ModSum)
}

func Panic() {
	if err := recover(); err != nil {
		logs.Info(err)
		os.Exit(1)
	}
}
